package bloomers

/**
* Controls the view of the page to register new seeds. Also save seeds to the specific user and writes them to the text file serving as the seed database
*/

class SeedzRegistrationController {

    def index() {}
    
    /**
    * creates an instance of a new seed from the params entered into the text boxes and dropdown boxes in the seed registration form
    */
    
    def createSeed(){
        def seedInstance = new Seedz()
        seedInstance.properties = params
        
        
        //seed.save()
        
        print seedInstance.hardiness
        
        
        redirect (controller:'UserHome')
        
        //return [seedInstance: seedInstance]
    }
    
    
    /**
    * creates an instance of a seed from the params given and saves it to the txt file serving as the seed database
    */
    
    def saveSeed(){
        def seed = new Seedz(params)
        
                 def seedzFile = new File( '/Users/hryals3/NetBeansProjects/Bloomers/grails-app/conf/Resources/bloomersSeedz.txt' )
        
        def seedz = Seedz.getAll()
        
        def species = "a"
        
        def driveInfo = [:]
            // Step through each line in the file
            seedzFile.eachLine { line ->
                // If the line isn't blank
                if( line.trim() ) {
                    // Split into a key and value
                    def seedzFields = line.split( '\t' ).collect { it.trim() }
                    species = species + " " + seedzFields[1]
                }
            }
            
        for(Seedz see : seedz){
           if(!species.contains(see.species))
           seedzFile.append("\n" + see.annual + "\t"
                        + see.genus + "\t"
                        + see.species + "\t"
                        + see.seedName + "\t"
                        + see.variety + "\t"
                        + see.forma + "\t"
                        + see.hardiness)
       }
        
        if (seed.save(flush: true)) {
            //print seed.hardiness
            //flash.message="${message(code: 'default.created.message', args: [message(code: 'seedz.label', default: 'Seedz'), seed.id])}"
            session.user.seedArr.add(seed)
            
    
            
            render(view:"/seedzRegView/index", model: [annual: seed.annual, genus: seed.genus, species: seed.species, seedName: seed.seedName, variety: seed.variety, forma: seed.forma, hardiness: seed.hardiness])
            //redirect(controller: "UserHome")
            
            //this gives the id number for the seed id: seed.id
            //should prob use this to assign to current user
        }
        else {
            render(view:"index",model: [seed: seed])
        }
    }
}
